//
//  CategoryViewController.m
//  liwushuo
//
//  Created by qf1 on 16/4/15.
//  Copyright (c) 2016年 ZJH. All rights reserved.
//

#import "CategoryViewController.h"
#import "CategoryTopicDetailViewController.h"
#import "CategoryDetailViewController.h"
#import "SelectView.h"
#import "SelectViewController.h"
#import "SelectDetailViewController.h"

@interface CategoryViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (retain,nonatomic)UITableView * tableView;
@property (retain,nonatomic)NSMutableArray * dataArray;
@property (retain,nonatomic)NSMutableArray * topicArray;
@property (retain,nonatomic)UIScrollView * scrollView;
@property (retain,nonatomic)UIScrollView * topicScroll;
@property (retain,nonatomic)UIScrollView * categoryScroll;
@property (retain,nonatomic)UIScrollView * navigaitonScroll;
@property (retain,nonatomic)UISegmentedControl * sgc;
@property (assign,nonatomic)int index;
@property (retain,nonatomic)NSMutableArray * secondDataArray;
@property (retain,nonatomic)NSMutableArray * indexArray;
@end

@implementation CategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.detailsLabelText = @"请稍后";
    [hud show:YES];
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self createView];
    [self getData];
    
}

- (void)awakeFromNib {
    [self setTabBarImage];
}

- (void)setTabBarImage{

    
    UIImage * image = [UIImage imageNamed:@"category2"];
//    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    [self.tabBarItem setSelectedImage:image];
}

- (void)segcAction:(UISegmentedControl *)sgc{
    [_scrollView setContentOffset:CGPointMake(sgc.selectedSegmentIndex * theScreenWidth, 0)];
}

- (void)createView{
    
    _sgc = [[UISegmentedControl alloc] initWithItems:@[@"攻略",@"礼物"]];
    _sgc.frame = CGRectMake(0, 0, 150, 30);
    
    _sgc.selectedSegmentIndex = 0;
    [_sgc addTarget:self action:@selector(segcAction:) forControlEvents:UIControlEventValueChanged];
    [self.navigationItem setTitleView:_sgc];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, theScreenHeight - 49)];
    _scrollView.contentSize = CGSizeMake(theScreenWidth * 2, theScreenHeight - 64);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, theScreenHeight - 64 - 49) style:UITableViewStyleGrouped];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    [_scrollView addSubview:_tableView];
    _navigaitonScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(theScreenWidth,40, 80, theScreenHeight - 64 - 49 - 40)];
    _navigaitonScroll.showsVerticalScrollIndicator = NO;
    _navigaitonScroll.delegate = self;
    [_scrollView addSubview:_navigaitonScroll];
    _categoryScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(theScreenWidth + 80,40,theScreenWidth - 80, theScreenHeight - 49 - 40 - 64)];
    //    _categoryScroll.showsVerticalScrollIndicator = NO;
    _categoryScroll.contentSize = CGSizeMake(theScreenWidth, theScreenHeight * 10);
    _categoryScroll.delegate = self;
    [_scrollView addSubview:_categoryScroll];
    [self.view addSubview:_scrollView];
    SelectView * view = [[SelectView alloc] initWithFrame:CGRectMake(theScreenWidth, 0, theScreenWidth, 40)];
    view.frame = CGRectMake(theScreenWidth, 0, theScreenWidth, 40);
    view.userInteractionEnabled = YES;
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectAction)];
    [view addGestureRecognizer:tap];
    [_scrollView addSubview:view];
    
}

#pragma mark 跳转到选礼神器页面
- (void)selectAction{
    SelectViewController * vc = [[SelectViewController alloc] init];
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)getData{
    NetWorkManager * manager = [[NetWorkManager alloc] init];
    __weak CategoryViewController * weakself = self;
    [manager getCategoryTopicDataWithUrl:@"http://api.liwushuo.com/v2/collections?limit=10&offset=0" andBlock:^(id respond) {
        _topicArray = [[NSMutableArray alloc] initWithArray:respond];
        
        [_tableView reloadData];
        [MBProgressHUD hideAllHUDsForView:weakself.view animated:YES];
    }];
//    ***************************
    [manager getCategoryDataWithUrl:@"http://api.liwushuo.com/v2/channel_groups/all" andBlock:^(id respond) {
        _dataArray = [[NSMutableArray alloc] initWithArray:respond];
        
        [_tableView reloadData];
    }];
//    ***************************
    [manager getCategorySecondDataWithUrl:@"http://api.liwushuo.com/v2/item_categories/tree" andBlock:^(id respond) {
        _secondDataArray = [[NSMutableArray alloc] initWithArray:respond];
        NSArray * array = [[NSArray alloc] initWithArray:respond];
        _navigaitonScroll.contentSize = CGSizeMake(80, 40 * array.count);
        for (int i = 0; i < array.count; i ++) {
            [_navigaitonScroll addSubview:({
                UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = CGRectMake(0, i * 40, 80, 40);
                [button setTitle:array[i][0] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
                button.titleLabel.font = [UIFont systemFontOfSize:13];
                button.titleLabel.textAlignment = NSTextAlignmentCenter;
                button.tag = 500 + i;
                button.backgroundColor = [UIColor colorWithRed: 250 / 255.0 green:250 / 255.0 blue:250 / 255.0 alpha:1];
                [button addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
                if (i == 0) {
                    button.selected = YES;
                }
                button;
            })];
        }
        
//    *************************************************
        [self analyzeDataToIndexArray:array];
        locationItem * lastItem = _indexArray[_indexArray.count - 1];
        _categoryScroll.contentSize = CGSizeMake(theScreenWidth - 80, lastItem.y + lastItem.height);
        _categoryScroll.delegate = self;
    for (int i = 0; i < array.count; i ++) {
        NSArray * imageArray = array[i];
        locationItem * locationItem = _indexArray[i];
        UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, locationItem.y - 30, theScreenWidth - 80, 20)];
        titleLabel.text = [NSString stringWithFormat:@"------%@------",imageArray[0]];
        titleLabel.textColor = [UIColor grayColor];
        titleLabel.font = [UIFont systemFontOfSize:12];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        [_categoryScroll addSubview:titleLabel];
        for (int j = 0; j < imageArray.count - 1; j ++) {
            UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake((theScreenWidth - 220 - 80) / 2.5 + j % 3 * ((theScreenWidth - 80) / 3), locationItem.y + j / 3 * 80, 55, 60)];
            SecondCategoryItem * item = imageArray[j + 1];
            [imageView setImageWithURL:[NSURL URLWithString:item.icon_url]];
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeAction:)];
            [imageView addGestureRecognizer:tap];
            [_categoryScroll addSubview:imageView];
            UILabel * namelabel = [[UILabel alloc] initWithFrame:CGRectMake(j % 3 * ((theScreenWidth - 80) / 3), locationItem.y + j / 3 * 80 + 60, ((theScreenWidth - 80) / 3), 20)];
//            第二个分类栏的跳转处理
            imageView.tag = 1000 * i + j * 10;
            namelabel.text = item.name;
            namelabel.font = [UIFont systemFontOfSize:10];
            namelabel.textAlignment = NSTextAlignmentCenter;
            namelabel.textColor = [UIColor grayColor];
            [_categoryScroll addSubview:namelabel];
            }
        }
    }];
}



#pragma mark tableview协议执行的方法

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return NO;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count + 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 70;
    }else
        return ([_dataArray[indexPath.section - 1] count] - 1) / 4 * 80 + 80;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString * cellId = @"cell1";
        UITableViewCell * cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            _topicScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 70)];
            _topicScroll.showsHorizontalScrollIndicator = NO;
            
        }
        _topicScroll.contentSize = CGSizeMake(100 * _topicArray.count, 70);
        [cell.contentView addSubview:_topicScroll];
        for (int i = 0; i < _topicArray.count; i ++) {
            CategoryTopicItem * item = _topicArray[i];
            [_topicScroll addSubview:({
                UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10 + 100 * i, 5, 90, 55)];
                imageView.userInteractionEnabled = YES;
                imageView.tag = 50 + i;
                [imageView setImageWithURL:[NSURL URLWithString:item.banner_image_url]];
                [imageView.layer setCornerRadius:5];
                [imageView.layer setMasksToBounds:YES];
                UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
                [imageView addGestureRecognizer:tap];
                imageView;
            })];
        }
        return cell;
    }else{
        static NSString * cellId = @"cell2";
        
        UITableViewCell * cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            for (int i = 0; i < [_dataArray[indexPath.section - 1] count] - 1; i ++) {
                
                [cell.contentView addSubview:({
                    UIImageView * imageView = [[UIImageView alloc] init];
                    imageView.frame = CGRectMake(i % 4 * theScreenWidth / 4.5  + (theScreenWidth - 200) / 5, i / 4 * 80, 50, 50);
                    imageView.tag = 100 * indexPath.section + i;
                    imageView;
                })];
            }
            for (int i = 0; i < [_dataArray[indexPath.section - 1] count] - 1; i ++) {
                [cell.contentView addSubview:({
                    UILabel * titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(i % 4 * theScreenWidth / 4.5 + (theScreenWidth - 200) / 5, i / 4 * 80 + 50, 50, 20)];
                    titleLabel.tag = 150 + i;
                    titleLabel.font = [UIFont systemFontOfSize:11];
                    titleLabel.textAlignment = NSTextAlignmentCenter;
                    titleLabel;
                })];
            }
        }
        for (int i = 0; i < [_dataArray[indexPath.section - 1] count] - 1; i ++) {
            CategoryItem * item = _dataArray[indexPath.section - 1][i];
            UIImageView * imageView = (UIImageView *)[cell.contentView viewWithTag:100 * indexPath.section + i];
            [imageView setImageWithURL:[NSURL URLWithString:item.icon_url]];
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [imageView addGestureRecognizer:tap];
            UILabel * titleLabel = (UILabel *)[cell.contentView viewWithTag:150 + i];
            titleLabel.text = item.name;
        }
        return cell;
    }
    
}

- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    if (tap.view.tag < 100) {
        
    CategoryTopicDetailViewController * vc = [[CategoryTopicDetailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        vc.banner = _topicArray[tap.view.tag - 50];
    }else{
        CategoryDetailViewController * vc = [[CategoryDetailViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        vc.item = _dataArray[tap.view.tag / 100 - 1][tap.view.tag % 100];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 40)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 40)];
        label.text = @"专题";
        label.font = [UIFont systemFontOfSize:13];
        [view addSubview:label];
        return view;
    }else{
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, theScreenWidth, 40)];
        view.backgroundColor = [UIColor whiteColor];
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 100, 25)];
        label.text = _dataArray[section - 1][[_dataArray[section - 1] count] - 1];
        label.font = [UIFont systemFontOfSize:12];
        [view addSubview:label];
        return view;
    }
}



- (void)changeAction:(UITapGestureRecognizer *)tap{
    SecondCategoryItem * item = _secondDataArray[tap.view.tag / 1000][tap.view.tag % 1000 / 10 + 1];
    SelectDetailViewController * vc = [[SelectDetailViewController alloc] init];
    vc.item = item;
    vc.titleName = item.name;
    [self.navigationController pushViewController:vc animated:NO];
}

- (void)btnAction:(UIButton *)btn{
    for (int i = 0; i < _secondDataArray.count; i ++) {
        UIButton * button = (UIButton *)[self.view viewWithTag:500 + i];
        button.selected = NO;
    }
    btn.selected = YES;
    locationItem * item = _indexArray[btn.tag - 500];
    [_categoryScroll setContentOffset:CGPointMake(0, item.y - 30) animated:YES];
    
}

#pragma mark 获取行高和位置的数组
- (void)analyzeDataToIndexArray:(NSArray *)array{
    _indexArray = [[NSMutableArray alloc] init];
    _index = 0;
    for (int i = 0; i < _secondDataArray.count; i ++) {
        locationItem * item = [[locationItem alloc] init];
        NSArray * arr = _secondDataArray[i];
        int count = 0;
        
        item.y = 40 + _index;
        if ((arr.count - 1) % 3 == 0) {
            count = (int)(arr.count - 1) / 3;
        }else
            count = (int)(arr.count - 1) / 3 + 1;
        _index = item.y + count * 80 + 20;
        item.height = count * 80;
        [_indexArray addObject:item];
    }
}

#pragma mark scroll执行代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (scrollView == _scrollView) {
        _sgc.selectedSegmentIndex = _scrollView.contentOffset.x / theScreenWidth;
    }
}

#pragma mark 按钮跳转
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    NSLog(@"%f",scrollView.contentOffset.y);
//    
//    if (scrollView == _categoryScroll) {
//        for (int i = 0; i < _indexArray.count; i ++) {
//            locationItem * item = _indexArray[i];
//            
//            if (_categoryScroll.contentOffset.y == (float)item.y || _categoryScroll.contentOffset.y == (float)item.y + 0.5) {
//                for (int j = 0; j < _secondDataArray.count; j ++) {
//                    UIButton * button = (UIButton *)[self.view viewWithTag:500 + j];
//                    button.selected = NO;
//                }
//                UIButton * button = (UIButton *)[self.view viewWithTag:500 + i];
//                button.selected = YES;
//            }
//        }
//    }
//}


- (void)viewWillAppear:(BOOL)animated{
    [self.tabBarController.tabBar setHidden:NO];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
